package repository

import (
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"
	"guns-excel/internal/app/model"
	"guns-excel/internal/pkg/util/result"
)

// 增加规则
func AddTimedTask(ctx *fiber.Ctx, p *model.TimedTask, db *gorm.DB) error {
	return db.Table("timed_task").Create(&p).Error
}

// 定时任务列表
func TimedTaskPageList(ctx *fiber.Ctx, pager *result.Pager, task *model.TimedTask, db *gorm.DB) ([]*model.TimedTask, int64, error) {
	timedTask := make([]*model.TimedTask, 0)
	var count int64
	db = db.Table("timed_task").Where("is_del", 0).Count(&count)
	if pager != nil {
		db = db.Offset((pager.PageIndex - 1) * pager.PageSize).Limit(pager.PageSize)
	}
	if err := db.Find(&timedTask).Error; err != nil {
		return nil, count, err
	}
	return timedTask, count, nil
}

func TimedTaskList(ctx *fiber.Ctx, task *model.TimedTask, db *gorm.DB) ([]*model.TimedTask, error) {
	timedTask := make([]*model.TimedTask, 0)
	db = db.Table("timed_task").Where("is_start", task.IsStart)
	if err := db.Find(&timedTask).Error; err != nil {
		return nil, err
	}
	return timedTask, nil
}

func TimedUpdate(ctx *fiber.Ctx, values interface{}, task *model.TimedTask, db *gorm.DB) error {
	return db.Table("timed_task").Where("func_name", task.FuncName).Updates(values).Error
}
